<?php
/**
* File that contains BusStopController class.
* @package busmap
*/

/**
* BusStopController class shows the user all buslines or only one.
* @package busmap
*/
class BusstopController extends Zend_Controller_Action
{

	/**
	* Initialize does nothing.
	*/
    public function init()
    {
        /* Initialize action controller here */
    }

	/**
	* Index fetches all busstops and sends them to view.
	*/
    public function indexAction()
    {
        $busstopMapper = new Application_Model_BusStopMapper();
        $this->view->entries = $busstopMapper->fetchAll();
    }

	/**
	* Function that removes the "busstop" route from the Router, because breadcrumbs wouldn't work with that route.
	* Then adds a new route, where the route is set to path directing to the busstop at hand. This route will be used by breadcrumbs.
	*/
	public function reRouteForOneBusstop($busstopName){
		$frontController = Zend_Controller_Front::getInstance();
		$router = $frontController->getRouter();
		$busstopRoute = $router->getRoute('busstop');
		$router->removeRoute('busstop');
		$newRoute = new Zend_Controller_Router_Route(
			'busstop/'.$busstopName,
			array(),
			array()

		);
		$router->addRoute('busstop', $newRoute);
		$this->view->navigation()->breadcrumbs()->setRenderInvisible(true);
	}
	
	/*
	* This function searches for a requested busstop by name.
	* Sends found busstop to view or sends an error message instead.
	*/
	public function onebusstopAction(){
		$busstopName = $this->_request->getParam('busstopName');
		$thisPage = $this->view->navigation()->getContainer()->findBy('label','Peatus');

		$this->reRouteForOneBusstop($busstopName);

		$thisPage->setActive(true);
		$thisPage->set('label', $busstopName);

		$busstop = new Application_Model_BusStop();
		$busstopMapper = new Application_Model_BusStopMapper();
		$busstopMapper->findByName($busstopName, $busstop);
		if($busstop->id){
			$this->view->entry = $busstop;
		}else{
			$this->view->errorMessage = 'Ei leitud bussipeatust nimega <b>'.$busstopName.'</b>';
		}
	}

	/**
	* This function is requested by editBuslines action from AdminController by Ajax when an administrator wants to select busstops.
	*/
	public function selectAction(){

        $busstopMapper = new Application_Model_BusStopMapper();
        $this->view->entries = $busstopMapper->fetchAll();
		$this->_helper->layout->disableLayout();

	}

	/**
	* This function is called to show a success message and refresh page if the select from a list generated by selectAction was successful.
	*/
	public function successAction(){
		$this->_helper->layout->disableLayout();

	}

}